package com.haidechizi.backup.sort1;

import java.util.Arrays;

public class RadixSort {

    public static void main(String[] args) {
        int[] arr = new int[]{899, 33, 5, 20, 144, 410, 6};
        radixSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void radixSort(int[] arr) {
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (max < arr[i]) {
                max = arr[i];
            }
        }

        int maxLength = String.valueOf(max).length();

        int[][] tempArr = new int[10][arr.length];

        int[] counts = new int[10];
        for (int i = 0, n = 1; i < maxLength; i++, n = n * 10) {
            for (int j = 0; j < arr.length; j++) {
                int ys = arr[j] / n % 10;
                tempArr[ys][counts[ys]] = arr[j];
                counts[ys]++;
            }
            // 将零食数组中的数据写会到原数组中
            int index = 0;
            for (int k = 0; k < counts.length; k++) {
                if (counts[k] > 0) {
                    for (int l = 0; l < counts[k]; l++) {
                        arr[index] = tempArr[k][l];
                        index++;
                    }
                    counts[k] = 0;
                }
            }
        }
    }
}
